#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <sys/socket.h>
#include <arpa/inet.h>
# define SERV_PORT 9527

//UDP服务器
void sys_err(const char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	int sockfd;
	int fret,i;//接受recvfrom返回，recvfrom函数返回读到的字节数
	char buf[4096], clit_ip[1024];

	struct sockaddr_in serv_addr, clit_addr;
	socklen_t clit_addr_len;

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(SERV_PORT);//本地字节序转网络字节序
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);//任意可用ip地址

	sockfd = socket(AF_INET,SOCK_DGRAM ,0);//这里用报文协议表示UDP
	if(sockfd == -1)
		sys_err("server socket create error");
	

	int ret = bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
	if(ret == -1)
		sys_err("server bind error");
	

	clit_addr_len = sizeof(clit_addr);
	while(1){

		fret = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&clit_addr, &clit_addr_len);//这里传出客户端地址，供下面sendto使用
		if(fret == -1)
			sys_err("recvfrom  error");
		
		printf("client ip:%s, port:%d\n", 
			inet_ntop(AF_INET, &clit_addr.sin_addr.s_addr, clit_ip, sizeof(clit_ip)),
			ntohs(clit_addr.sin_port));

		write(STDOUT_FILENO, buf ,fret);
		printf("\n");

		for(i=0; i<fret; i++){
			buf[i] = toupper(buf[i]);//对数据进行操作
		}

		fret = sendto(sockfd, buf, fret, 0, (struct sockaddr *)&clit_addr, sizeof(clit_addr));//recvfrom里最后一个参数是传入传出参数。这里是传入参数，所以不同
		if(fret == -1)
			sys_err("sendto error");
	}

	close(sockfd);//关闭连接

	return 0;
}

